package ext.drawing;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ext.com.core.CoreUtil;
import ext.tianma.part.PartWorkflowUtil;
import wt.doc.WTDocument;
import wt.doc.WTDocumentMaster;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.pds.StatementSpec;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionServerHelper;
import wt.util.WTException;

/**
 * 文档借阅查询业务类
 * 
 * @author lilin
 * 
 */
@Controller
@RequestMapping({ "/borrowDra" })
public class BorrowDra {

	/**
	 * 根据页面传的编号返回图文档名称
	 * 
	 * @param numType
	 * @param number
	 * @return
	 */
	@RequestMapping(value = "/dra", method = { RequestMethod.POST, RequestMethod.GET })
	public static void getWTDocByNumber(@RequestParam(value = "numType", required = true) String numType,
			@RequestParam(value = "number", required = true) String number, HttpServletResponse response)
			throws Exception {
		JSONObject ob = new JSONObject();
		JSONArray array = new JSONArray();
		PrintWriter out = response.getWriter();
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false);
		try {
			// 当查询类型是文档编号时
			if ("wtDocNum".equals(numType)) {
				WTDocumentMaster docMaster = null;
				QuerySpec qs = new QuerySpec(WTDocumentMaster.class);
				SearchCondition sc = new SearchCondition(WTDocumentMaster.class, WTDocumentMaster.NUMBER,
						SearchCondition.EQUAL, number.trim(), false);
				qs.appendWhere(sc, new int[] { 0 });
				QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);// 查询文档编号
				// 查询不到时
				if (qr.size() == 0) {
					String str = "error";
					ob.put("status", str);
					out.print(ob.toString());
					return;
				}
				ob.put("status", "success");
				// 查询到
				while (qr.hasMoreElements()) {
					JSONObject ob1 = new JSONObject();
					docMaster = (WTDocumentMaster) qr.nextElement();
					WTDocument doc = BorrowWorkflowUtil.getLatestDocument(docMaster);// 获取最新版本
					String sts = doc.getState().getState().getStringValue();
					if ("wt.lifecycle.State.RELEASED".equals(sts)) {// 已发布状态
						ob1.put("name", doc.getName());
						ob1.put("number", doc.getNumber());
						array.put(ob1);
					} else {
						String str = "errorReleased";
						ob.put("status", str);
						out.print(ob.toString());
						return;
					}
				}
				// 当查询类型是部件编号时
			} else if ("wtPartNum".equals(numType)) {
				WTPart part = null;
				QuerySpec qs = new QuerySpec(WTPartMaster.class);
				SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL,
						number.trim(), false);
				qs.appendWhere(sc, new int[] { 0 });
				QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
				// 查询不到时
				if (qr.size() == 0) {
					String str = "errorPart";
					ob.put("status", str);
					out.print(ob.toString());
					return;
				}
				ob.put("status", "success");
				// 查到时
				while (qr.hasMoreElements()) {
					WTPartMaster master = (WTPartMaster) qr.nextElement();
					// 获取物料的其他所有视图对象
					part = BorrowWorkflowUtil.getLatestPart(master);// 根据WTPartMaster获得最新版WTPart
					WTArrayList partList = new WTArrayList();
					if (part != null) {
						partList = PartWorkflowUtil.getAllPartViews(part);// 获取所有视图
						part = CoreUtil.getWTPartByNumberAndView(part.getNumber(), "Design");// 获取design试图
						partList.add(part);// 增加到list中
					}
					List<WTDocument> resultAll = new ArrayList<WTDocument>();
					for (int i = 0; i < partList.size(); i++) {
						WTPart wtpart = null;
						wtpart = (WTPart) partList.getPersistable(i);
						List<WTDocument> result = BorrowWorkflowUtil.getReferenceDoc(wtpart);// 根据part得到参考关系的文档集合
						List<WTDocument> resultReference = BorrowWorkflowUtil.getDescribeDoc(wtpart);// 根据part得到描述关系的文档集合
						resultAll.addAll(result);// 将两个集合合并成一个
						resultAll.addAll(resultReference);// 将两个集合合并成一个

					}

					resultAll = new ArrayList<WTDocument>(new HashSet(resultAll));// 去重
					if (resultAll.size() == 0) {
						String str = "errordoc";
						ob.put("status", str);
						out.print(ob.toString());
						return;
					} else {
						boolean released = false;
						for (int i = 0; i < resultAll.size(); i++) {
							WTDocument doc = resultAll.get(i);
							String sts = doc.getState().getState().getStringValue();
							if ("wt.lifecycle.State.RELEASED".equals(sts)) {// 已发布状态
								released = true;
								JSONObject ob1 = new JSONObject();
								ob1.put("name", doc.getName());
								ob1.put("number", doc.getNumber());
								array.put(ob1);
							}
						}
						if (!released) {
							String str = "errorReleased";
							ob.put("status", str);
							out.print(ob.toString());
							return;
						}
					}

				}
			}
			ob.put("data", array);
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			SessionServerHelper.manager.setAccessEnforced(flag);
		}
		out.print(ob.toString());
		return;
	}

}
